//
//  AppDelegate.m
//  IpadTestB
//
//  Created by edianzu on 2017/6/26.
//  Copyright © 2017年 ruilai. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginNewViewController.h"
#import "ReloadDataViewController.h"
#import "LoginNewViewController.h"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds] ];
    
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
////
//    [user removeObjectForKey:@"AllData"];
//    [user synchronize];
//    NSLog(@"jianren%@",[user objectForKey:@"AllData"]);

   
    
//    [user setObject:nil forKey:@"AllData"];
//    [user removeObjectForKey:@"deleteChildArray"];
//    [user removeObjectForKey:@"deleteClassArray"];
//    [user removeObjectForKey:@"CreatPlanId"];
//    [user removeObjectForKey:@"CreatClassId"];
//    [user removeObjectForKey:@"CreatProjectId"];
//    [user removeObjectForKey:@"deleteChildArray"];
//    [user removeObjectForKey:@"deleteClassArray"];
//    
    
    if ([user objectForKey:@"CreatMasterId"]==nil) {
        [user setObject:@-100 forKey:@"CreatMasterId"];//营销新添加孩子
    }
    if ([user objectForKey:@"CreatChildId"]==nil) {
        [user setObject:@-100 forKey:@"CreatChildId"];//非营销新添加孩子
    }
    if ([user objectForKey:@"CreatPlanId"]==nil) {
        [user setObject:@-100 forKey:@"CreatPlanId"];//新建测试计划
    }
    if ([user objectForKey:@"CreatClassId"]==nil) {
        [user setObject:@-100 forKey:@"CreatClassId"];//新加班级
    }
    if ([user objectForKey:@"CreatProjectId"]==nil) {
        [user setObject:@-100 forKey:@"CreatProjectId"];//新加班级
    }
    if ([user objectForKey:@"deleteChildArray"]==nil) {//删除孩子，保存被删除的孩子ID
        NSMutableArray * DCA = [[NSMutableArray alloc]init];
        NSMutableDictionary * dcd = [[NSMutableDictionary alloc]init];
        [dcd setObject:DCA forKey:@"deleteChildArray"];
        NSData * data = [NSJSONSerialization dataWithJSONObject:dcd options:NSJSONWritingPrettyPrinted error:nil];
        NSString* deleteChild = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [user setObject:deleteChild forKey:@"deleteChildArray"];
        [user synchronize];
    }
    if ([user objectForKey:@"deleteClassArray"]==nil) {//删除班级，保存被删除的班级ID
        NSMutableArray * DCA = [[NSMutableArray alloc]init];
        NSMutableDictionary * dcd = [[NSMutableDictionary alloc]init];
        [dcd setObject:DCA forKey:@"deleteClassArray"];
        NSData * data = [NSJSONSerialization dataWithJSONObject:dcd options:NSJSONWritingPrettyPrinted error:nil];
        NSString* deleteChild = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [user setObject:deleteChild forKey:@"deleteClassArray"];
        [user synchronize];
    }
    if ([user objectForKey:@"deletePlanArray"]==nil) {//删除测试计划，保存被删除的计划ID
        NSMutableArray * DCA = [[NSMutableArray alloc]init];
        NSMutableDictionary * dcd = [[NSMutableDictionary alloc]init];
        [dcd setObject:DCA forKey:@"deletePlanArray"];
        NSData * data = [NSJSONSerialization dataWithJSONObject:dcd options:NSJSONWritingPrettyPrinted error:nil];
        NSString* deleteChild = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [user setObject:deleteChild forKey:@"deletePlanArray"];
        [user synchronize];
    }
    if ([user objectForKey:@"deleteMasterArray"]==nil) {//删除营销孩子，保存被删除的营销孩子ID
        NSMutableArray * DCA = [[NSMutableArray alloc]init];
        NSMutableDictionary * dcd = [[NSMutableDictionary alloc]init];
        [dcd setObject:DCA forKey:@"deleteMasterArray"];
        NSData * data = [NSJSONSerialization dataWithJSONObject:dcd options:NSJSONWritingPrettyPrinted error:nil];
        NSString* deleteChild = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [user setObject:deleteChild forKey:@"deleteMasterArray"];
        [user synchronize];
    }
    
    
    
    //
    

    //网络状态
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
            {
                // 位置网络
                //                    [self pressLogin];
                NSLog(@"位置网络");
            }
                break;
            case AFNetworkReachabilityStatusNotReachable:
            {
                // 无法联网
                NSLog(@"无法联网");
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                // WIFI
                NSLog(@"当前使用的是WIFI网络");
                //                    [self pressLogin];
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                // 手机自带网络
                //                    [self pressLogin];
                NSLog(@"当前在2g/3g/4g网络下");
            }
        }
    }];
    
    NSString* newStates = [self getNetWorkStates];
    NSLog(@"%@",newStates);
    if ([newStates isEqualToString:@"无网络"]) {
        if ([user objectForKey:@"AllData"] == nil  ) {
            NSLog(@"aaaaaaa");
            LoginNewViewController * lvc = [[LoginNewViewController alloc]init];
            UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:lvc];
            navi.navigationBar.barTintColor = [HexColor colorWithHexString:Green_Main];
            navi.navigationBar.translucent = NO;
            [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
            self.window.rootViewController = navi;
        }else{
            NSLog(@"bbbbbbb");
            ReloadDataViewController * rlt = [[ReloadDataViewController alloc]init];
            UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:rlt];
            navi.navigationBar.barTintColor = [HexColor colorWithHexString:Green_Main];
            navi.navigationBar.translucent = NO;
            [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
            self.window.rootViewController = navi;
        }
        
    }else{
        
        if ([user objectForKey:@"PassWord"] == nil) {
            LoginNewViewController * lvc = [[LoginNewViewController alloc]init];
            UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:lvc];
            navi.navigationBar.barTintColor = [HexColor colorWithHexString:Green_Main];
            navi.navigationBar.translucent = NO;
            [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
            self.window.rootViewController = navi;
        }else{
            [self pressLogin];
            ReloadDataViewController * rlt = [[ReloadDataViewController alloc]init];
            UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:rlt];
            navi.navigationBar.barTintColor = [HexColor colorWithHexString:Green_Main];
            navi.navigationBar.translucent = NO;
            [[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            [[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
            self.window.rootViewController = navi;
            //自动登录
            
        }
    }
    
    
//    self.window.backgroundColor = [UIColor clearColor];
//    UINavigationController * navi = [[UINavigationController alloc]initWithRootViewController:[[NSClassFromString(@"LoginNewViewController")alloc]init]];
//    self.window.rootViewController = navi;
    [self.window makeKeyAndVisible];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:@"UIApplicationDidEnterBackgroundNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(comeHome:) name:@"UIApplicationDidEnterBackgroundNotification" object:nil];

    return YES;
}

//只用系统的终止方法，实测不行。必须加入监听自定义方法。判断APP 停止，移除登录标记islogin
- (void)comeHome:(UIApplication *)application {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //移除UserDefaults中存储的用户信息
    [userDefaults removeObjectForKey:@"isLogin"];
    
    NSLog(@"进入后台");
}

- (NSString *)getNetWorkStates{
    UIApplication *app = [UIApplication sharedApplication];
    NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];
    NSString *state = [[NSString alloc]init];
    int netType = 0;
    //获取到网络返回码
    for (id child in children) {
        if ([child isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {
            //获取到状态栏
            netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];
            
            switch (netType) {
                case 0:
                    state = @"无网络";
                    //无网模式
                    break;
                case 1:
                    state =  @"2G";
                    break;
                case 2:
                    state =  @"3G";
                    break;
                case 3:
                    state =   @"4G";
                    break;
                case 5:
                {
                    state =  @"wifi";
                    break;
                default:
                    break;
                }
            }
        }
        //根据状态选择
    }
    return state;
}
#pragma mark  登陆
-(void)pressLogin{
#if 0
    NSLog(@"开始登陆");
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *cookieArray = [NSArray arrayWithArray:[cookieJar cookies]];
    for (NSHTTPCookie *obj in cookieArray) {
        //        NSLog(@"现在的COOKIE %@",obj);
        [cookieJar deleteCookie:obj];
        
    }
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
//    NSLog(@"LLLLLLLLLLLLLL%@",[user objectForKey:@"isLogin"]);
//    if (![[user objectForKey:@"isLogin"] isEqualToString:@"isLogin"]) {
    
        NSString * urls = @"/authenticate/credentials";
        NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
        NSDictionary *parama = @{@"Username":[user objectForKey:@"UserName"],@"Password":[user objectForKey:@"PassWord"]};
        [[HttpRequest sharedInstance] getWithURLString:url parameters:parama success:^(id responseObject) {
            NSLog(@"登陆成功");
//            NSString * str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
//            NSLog(@"responseObject数据转成了json类型的数据 ＝ %@",str);
//            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//            NSDictionary * dic = dict[@"Meta"];
//            NSString * companyName = dict[@"DisplayName"];
            
//            [user setObject:dic[@"AgencyId"] forKey:@"AgencyId"];
            NSString * isLogin = @"isLogin";
            [user setObject:isLogin forKey:@"isLogin"];
            
            
        } failure:^(NSError *error) {
            
        }];
//    }
#endif
    LoginNewViewController *newVC = [LoginNewViewController new];
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    
    //NSString * urls = @"/authenticate/credentials";
    //NSString * url = [NSString stringWithFormat:@"%@%@",URL,urls];
   // NSDictionary *parama = @{@"Username":[user objectForKey:@"UserName"],@"Password":[user objectForKey:@"PassWord"]};
    newVC.userNameText.text = [user objectForKey:@"UserName"];
    newVC.passWordText.text = [user objectForKey:@"PassWord"];
    [newVC pressLogin];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
